package com.gqb.ServerSocket;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

public class ThrededEchoServer {
	public static void main(String[] args) {
		try {
			int i=1;
			ServerSocket serverSocket=new ServerSocket(8190);
			while(true){
				Socket incoming=serverSocket.accept();
				System.out.println("spawning "+i);
				Thread thread=new Thread(new ThreadedEchoHandler(incoming));
				thread.start();
				i++;
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
class ThreadedEchoHandler implements Runnable{
	private Socket incoming;
	
	public ThreadedEchoHandler(Socket incoming) {
		super();
		this.incoming = incoming;
	}

	@Override
	public void run() {
		try {
			try{
				InputStream inputStream=incoming.getInputStream();
				OutputStream outputStream=incoming.getOutputStream();
				Scanner in =new Scanner(inputStream);
				PrintWriter outPrintWriter=new PrintWriter(outputStream,true);
				outPrintWriter.println("Hello Enter bye to exit");
				
				boolean done=false;
				while(!done&&in.hasNextLine()){
					String line=in.nextLine();
					outPrintWriter.println("Echo: "+line);
					if(line.trim().equals("bye"))
						done=true;
					
				}
			}finally{
				incoming.close();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
}
